package cn.kgc.common.security.config;



import cn.kgc.common.security.filter.TokenAuthorityFilter;
import cn.kgc.common.security.filter.TokenLoginFilter;
import cn.kgc.common.util.RedisUtil;
import cn.kgc.api.service.UsersService;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.annotation.Resource;

/**
 * @Author: kgc
 * @Date: 2024-04-09
 * @Description: Security配置类
 * @Version: v1.0
 */
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Resource
    private UserDetailsService userDetailsService;

    @Resource
    private RedisUtil redisUtil;
    @Resource
    private UsersService usersService;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //指定userDetailService实体类
        auth.userDetailsService(userDetailsService);
    }

    /**
     * 配置SpringSecurity忽略地址
     * @param web
     * @throws Exception
     */
    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers(
                "/favicon.ico",
                "/swagger-resources/**",
                "/webjars/**",
                "/v2/**",
                "/swagger-ui.html/**",
                "/doc.html"
        );
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/users/login")
                .permitAll().anyRequest().authenticated()

                .and()
                .csrf().disable()  //防止csrf攻击
                .cors()     //支持跨域

                .and()
                .addFilterBefore(
                        new TokenAuthorityFilter(usersService,redisUtil),
                        UsernamePasswordAuthenticationFilter.class
                ).addFilter(
                        new TokenLoginFilter(this.authenticationManager())
                ).sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    }
}
